<?php
include_once 'php_mailer/class.phpmailer.php';
?>

<?php
/** Load web page by url parameter ************************************************
 * @author	Roam Cat
 * @method	js_location
 * @param	url (to load that web page)
 * ************************************************************************
 */
function js_location( $URL = false ) {
	
	if( $URL != false ) {
	
		echo ( "<script>
			try {
				parent.location.replace ( '".$URL."');
			}catch ( exception ) {
				location.replace( '".$URL."');
			}
			</script>" );
		return;
	
	} else
		echo ( "<script>
			try {
				parent.location.replace ('". $_SERVER[ "HTTP_REFERER" ]."');
			}catch ( exception ) {
				location.replace('".$_SERVER[ "HTTP_REFERER" ]."');
			}
		</script>" );
}

/** Upload Image To Server ************************************************
 * @author Roam Cat
 * 
 * @param	image_file (name of control file of HTML page) 
 * @param	pathfile (path to save image)
 * @param	image_name (name of image)
 * ************************************************************************
 */
function upload_image($image_file,$pathfile, $image_name = null){
	
	if ((($_FILES[$image_file]["type"] == "image/gif")
	|| ($_FILES[$image_file]["type"] == "image/jpeg")
	|| ($_FILES[$image_file]["type"] == "image/pjpeg"))
	&& ($_FILES[$image_file]["size"] < 2000000))//2,000,000:2MB
	{
		
		if ($_FILES[$image_file]["error"] > 0)
			return "-1";
		else{
			if (file_exists("../".$pathfile."/".$_FILES[$image_file]["name"]))
				return "-2";
			else{
				move_uploaded_file($_FILES[$image_file]["tmp_name"],"../".$pathfile."/".$image_name."_".date("Ymd_Hms").".jpg");
				return $image_name."_".date("Ymd_Hms").".jpg";
			}
		}
	}
	else
		return "-3";
}


/** Send Email using gmail account ************************************************
 * @author Roam Cat
 *
 * @param	body (name of control file of HTML page)
 * @param	mailfrom (path to save image)
 * @param	mailpass (name of image)
 * @param	userfrom (path to save image)
 * @param	subject (name of image)
 * @param	mailto (path to save image)
 * @param	userto (name of image)
 * ************************************************************************
 */
function phpmailer_send($body,$mailfrom,$mailpass,$userfrom,$subject,$mailto,$userto){
	$mail				= new PHPMailer();
		
	$body				= $body;
	$body				= eregi_replace("[\]",'',$body);
		
	$mail->IsSMTP();
	$mail->SMTPAuth		= true;                  // enable SMTP authentication
	$mail->SMTPSecure	= "ssl";                 // sets the prefix to the servier
	$mail->Host			= "smtp.gmail.com";      // sets GMAIL as the SMTP server
	$mail->Port			= 465;                   // set the SMTP port for the GMAIL server
		
	$mail->CharSet		= "utf-8";
	$mail->Username		= $mailfrom;			//"shop@neowiz.vn"; GMAIL username
	$mail->Password		= $mailpass;			//"neowiz@123"; GMAIL password
		
	$mail->AddReplyTo($mailfrom,$userfrom);
		
	$mail->From			= $mailfrom;
	$mail->FromName		= $userfrom;
		
	$mail->Subject		= $subject;
		
	$mail->AltBody		= "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
	$mail->WordWrap		= 50; // set word wrap
		
	$mail->MsgHTML($body);
		
	$mail->AddAddress($mailto,$userto);
		
	//$mail->AddAttachment("images/phpmailer.gif");             // attachment
		
	$mail->IsHTML(true); // send as HTML
		
	if(!$mail->Send()) {
		echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>";
		return 0;
	} else {
		return 1;
	}
}

/** Set up random string ************************************************
 * @author	liveonaware
 * @link	http://php.net/manual/en/function.rand.php
 * 
 * @param	$i_length length to create string
 * ************************************************************************
 */
function get_random_string($i_length) {
	//To Pull $i_length Unique Random Values Out Of AlphaNumeric

	//removed number 0, capital o, number 1 and small L
	//Total: keys = 32, elements = 33
	$characters = array(
			"A","B","C","D","E","F","G","H","J","K","L","M",
			"N","P","Q","R","S","T","U","V","W","X","Y","Z",
			"1","2","3","4","5","6","7","8","9");
	
	//make an "empty container" or array for our keys
	$keys = array();
	
	//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
	while(count($keys) < $i_length) {
		//"0" because we use this to FIND ARRAY KEYS which has a 0 value
		//"-1" because were only concerned of number of keys which is 32 not 33
		//count($characters) = 33
		$x = mt_rand(0, count($characters)-1);
		if(!in_array($x, $keys)) {
			$keys[] = $x;
		}
	}
	
	$random_chars="";
	foreach($keys as $key){
		$random_chars .= $characters[$key];
	}
	
	return $random_chars;
}


/** Create paging for array of Items ************************************************
 * @author	RoamCat
 *
 * @param	$i_totalItem: length to create string
 * @param	$i_amountPerPage:
 * @param	$i_currentPage: get current page of Items
 * ************************************************************************
 */
function CreatPaging ($i_totalItem, $i_amountPerPage, $i_currentPage)
{
	$i_totalPage = 0;
	//Calculate amount of page
	if($i_totalItem % $i_amountPerPage == 0)
		$i_totalPage = $i_totalItem / $i_amountPerPage;
	else
		$i_totalPage = (int) ($i_totalItem / $i_amountPerPage) + 1;
	
	
	echo "<div class=\"box_paging\">";	
	echo "<a href=\"javascript:void(0);\" onclick=\"load_list(1)\">◄</a> ";

	$iBatDau	= 1;
	$iketthuc	= $i_totalPage;
		
	if (($i_currentPage - 4)>1) $iBatDau = $i_currentPage - 4;
	
	if(($i_currentPage + 4) < $i_totalPage) $iketthuc = $i_currentPage + 4;
	
	if(($iBatDau -1) >= 1) echo ".... ";
	
	for ($i = $iBatDau; $i <= $iketthuc; $i++)
	{		
		if($i==$i_currentPage)
			echo "<a href='javascript:void(0);' class='selected_page'>".$i."</a> ";
		else
			echo "<a href='javascript:void(0);' onclick='load_list(".$i.")'>".$i."</a> ";
	}
		
	if(($iketthuc +1) <= $i_totalPage)
		echo " ....";
	
	echo "<a href=\"javascript:void(0);\" onclick=\"load_list(".$i_totalPage.")\">►</a>";
	echo "</div>";
}

/** upload file to temporation folder  ************************************************
 * @author	Unknow
 * @method	uploadFileAjax
 * ************************************************************************
 */
function uploadFileAjax($arr_types, $o_fileInputName)
{
	$s_error = "";
	$s_msg = "";
	
	if(!empty($_FILES[$o_fileInputName]['error']))
	{
		switch($_FILES[$o_fileInputName]['error'])
		{
	
			case '1':
				$s_error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$s_error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$s_error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$s_error = 'No file was uploaded.';
				break;
	
			case '6':
				$s_error = 'Missing a temporary folder';
				break;
			case '7':
				$s_error = 'Failed to write file to disk';
				break;
			case '8':
				$s_error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$s_error = 'No error code avaiable';
		}//end switch
		
		$arr_error = array("error" => $s_error);
		return $arr_error;

	}//End if(!empty($_FILES[$o_fileInputName]['error']))
	elseif(empty($_FILES[$o_fileInputName]['tmp_name']) || $_FILES[$o_fileInputName]['tmp_name'] == 'none')
	{
		$arr_error = array("error" => "No file was uploaded..");
		return $arr_error;
	}
	else
	{
		if ($arr_types == null || in_array($_FILES[$o_fileInputName]["type"], $arr_types))
		{
			$date_insert = new DateTime();
			
			$s_fileurl = "./public/file_temp/".$date_insert->format("Ymd").$_FILES[$o_fileInputName]["name"];
			move_uploaded_file($_FILES[$o_fileInputName]["tmp_name"],$s_fileurl);
			
			return $s_fileurl;
		}//End if (in_array($_FILES[$o_file_element]["type"], $arr_types))
		else
		{
			$arr_error = array("error" => "Định dạng tập tin không được hỗ trợ, hãy chọn tập tin có định dạng ". implode(", ", $arr_types));
			return $arr_error;
		}
	}// End else
}


/** upload file to temporation folder  ************************************************
 * @author	Unknow
 * @method	uploadImageAjax
 * ************************************************************************
 */
function uploadImageAjax($arr_types, $o_fileInputName, $s_destinationFolder, $i_width, $i_height, $s_imageName = null)
{
	$s_error			= "";
	$s_msg 				= "";
	$s_FileExtension	= "";

	if(!empty($_FILES[$o_fileInputName]['error']))
	{
		switch($_FILES[$o_fileInputName]['error'])
		{

			case '1':
				$s_error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$s_error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$s_error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$s_error = 'No file was uploaded.';
				break;

			case '6':
				$s_error = 'Missing a temporary folder';
				break;
			case '7':
				$s_error = 'Failed to write file to disk';
				break;
			case '8':
				$s_error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$s_error = 'No error code avaiable';
		}//end switch

		$arr_error = array("error" => $s_error);
		return $arr_error;

	}//End if(!empty($_FILES[$o_fileInputName]['error']))
	elseif(empty($_FILES[$o_fileInputName]['tmp_name']) || $_FILES[$o_fileInputName]['tmp_name'] == 'none')
	{
		$arr_error = array("error" => "No file was uploaded..");
		return $arr_error;
	}
	else
	{
		$s_FileExtension = pathinfo($_FILES[$o_fileInputName]["name"])["extension"];
		
		if ($arr_types == null || in_array(strtolower($s_FileExtension), $arr_types))
		{
			$date_insert = new DateTime();
				
			$s_fileurl = $s_destinationFolder."/".$date_insert->format("Ymd").$_FILES[$o_fileInputName]["name"];
			if( !is_null($s_imageName))
			{
			    $s_fileurl = $s_destinationFolder."/".$s_imageName.".".$s_FileExtension;
			}
			$source			= file_get_contents($_FILES[$o_fileInputName]["tmp_name"]);
			$destination	= $s_fileurl;
				
			imageresize($source, $destination, $i_width, $i_height, false, 100);
				
			//for security reason, we force to remove all uploaded file
			@unlink($_FILES[$o_file_element]);
				
			return $s_fileurl;
		}//End if (in_array($_FILES[$o_file_element]["type"], $arr_types))
		else
		{
			$arr_error = array("error" => "Định dạng tập tin không được hỗ trợ, hãy chọn tập tin có định dạng ". implode(", ", $arr_types));
			return $arr_error;
		}
	}// End else
}


/** resize to smaller image  ************************************************
 * @author	Unknow
 * @method	imageresize
 * ************************************************************************
 */
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 100) 
{
	$quality = $quality ? $quality : 100;
	$image = imagecreatefromstring($source);
	if ($image) 
	{
		// Get dimensions
		$w = imagesx($image);
		$h = imagesy($image);
		if (($width && $w > $width) || ($height && $h > $height)) {
			$ratio = $w / $h;
			if (($ratio >= 1 || $height == 0) && $width && !$crop) {
				$new_height = $width / $ratio;
				$new_width = $width;
			} elseif ($crop && $ratio <= ($width / $height)) {
				$new_height = $width / $ratio;
				$new_width = $width;
			} else {
				$new_width = $height * $ratio;
				$new_height = $height;
			}
		} else {
			$new_width = $w;
			$new_height = $h;
		}
		$x_mid = $new_width * .5;  //horizontal middle
		$y_mid = $new_height * .5; //vertical middle
		// Resample
		error_log('height: '.$new_height.' - width: '.$new_width);
		$new = imagecreatetruecolor(round($new_width), round($new_height));
		imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
		// Crop
		if ($crop) {
			$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
			imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
			//($y_mid - ($height * .5))
		}
		// Output
		// Enable interlancing [for progressive JPEG]
		imageinterlace($crop ? $crop : $new, true);

		$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
		if ($dext == '') {
			$dext = $ext;
			$destination .= '.' . $ext;
		}
		switch ($dext) {
			case 'jpeg':
			case 'jpg':
				imagejpeg($crop ? $crop : $new, $destination, $quality);
				break;
			case 'png':
				$pngQuality = ($quality - 100) / 11.111111;
				$pngQuality = round(abs($pngQuality));
				imagepng($crop ? $crop : $new, $destination, $pngQuality);
				break;
			case 'gif':
				imagegif($crop ? $crop : $new, $destination);
				break;
		}
		@imagedestroy($image);
		@imagedestroy($new);
		@imagedestroy($crop);
	}
}
?>